package j.framework.util;

import j.framework.core.LoginUser;
import j.util.New;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 对java bean调用的一些常用操作的封装
 * User: jason
 * Date: 2014/12/16 17:02
 */
public class BeanUtils {
    /**
     * 根据bean的属性名称获取其对应的get方法
     * @param beanClass
     * @param propertyName
     * @return
     */
    public static String getBeanGetMethodName(Class<?> beanClass,String propertyName){
        String beanGetMethodName = null;
        try {
            Field field = beanClass.getDeclaredField(propertyName);
            if(null!=field){
                //将propertyName的首字母小写
                propertyName = Character.toUpperCase(propertyName.charAt(0))+propertyName.substring(1);
                if(field.getType().equals(boolean.class)){
                    beanGetMethodName = "is"+propertyName;
                }else{
                    beanGetMethodName = "get"+propertyName;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return beanGetMethodName;
    }

    public static void main(String[] args) {
        LoginUser user = new LoginUser();
        user.setName("abc");
        System.out.println(BeanUtils.fromBeanToMap(user));
    }

    public static Map<String, Object> fromBeanToMap(Object bean) {
        Map<String, Object> map = New.map();
        Class<?> clazz = bean.getClass();
        List<Method> methods = New.list();
        //再获取其父类的方法
        while(clazz!=null && !clazz.equals(Object.class)){
            methods.addAll(Arrays.asList(clazz.getDeclaredMethods()));
            clazz = clazz.getSuperclass();
        }
        String key;
        Object objValue;
        try {
            for (Method m : methods) {
                key = m.getName();
                if (key.startsWith("is")) {
                    key = Character.toLowerCase(key.charAt(2)) + key.substring(3);
                } else if (key.startsWith("get")) {
                    key = Character.toLowerCase(key.charAt(3)) + key.substring(4);
                } else {
                    continue;
                }
                objValue = m.invoke(bean);
                if (null != objValue) {
                    map.put(key, objValue);
                }
            }
        }catch (Exception e){
            throw new RuntimeException("在将bean"+bean.getClass().getName()+"转换为map时出错，异常："+e.getMessage());
        }
        return map;
    }
}
